<?php
ob_start("ob_gzhandler");
if (!isset($_SESSION))
    session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <?php
    try {
        //require('../../Smarty/libs/Smarty.class.php');
        require('../../Smarty/libs/SmartyBC.class.php');
        include_once 'API/APIObject.php';
        include_once 'API/Code/Filter.php';
        include_once 'API/Code/RoomGroup.php';
        include_once 'API/Utils.php';
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }

    // Smarty configurarion
    $smarty = new Smarty;
    $smarty->setTemplateDir('./smarty/templates/');
    $smarty->setCompileDir('./smarty/templates_c/');
    $smarty->setConfigDir('./smarty/configs/');
    $smarty->setCacheDir('./smarty/cache/');
	
	//$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);

    $_SESSION['logged_bool'] = (isset($_SESSION['logged_bool'])) ? $_SESSION['logged_bool'] : false;
    $status = $_SESSION['logged_bool'];
    $smarty->assign("logged", $status);

    // Field Variables
    $errorUrl = './errorPage.php';
    $continue = true;
    $roomCount = 0;
    $rooms = array();

    // Hardcoded Variables
    $numberOfResults = 20;
    $countryCode = NULL;
    $stateProvince = NULL;

    /* Connect to the database and retrieve data */
    //mysql_connect("localhost:3306", "root", "expedia") or die("Unable to connect to MySQL " . mysql_error());
    mysql_connect("localhost:3306", "root", "expedia") or die("Unable to connect to MySQL " . mysql_error());
    @mysql_select_db("eandb") or die("Unable to select database " . mysql_error());

    $term = trim(strip_tags($_POST['destination'])); //retrieve the search term that autocomplete sends
    $pos = stripos($term, ',');

    // if $pos is false that means that no comma has been found and everything is in order
    if ($pos != false) {
        $term = substr($term, 0, $pos);
    }

    $qstring = "SELECT DISTINCT City AS value FROM activepropertylist WHERE City = '" . $term . "'";
    $result = mysql_query($qstring) or die(mysql_error()); //query the database for entries containing the term

    /* Check to see if the destination exists */
    $res = mysql_fetch_array($result, MYSQL_ASSOC);

    if (empty($res)) {
        /* If the destination is wrong set Session['searchError'] message and
         * head over to the error page */
        $_SESSION['searchError'] = "Sorry, no available hotels were found. Please try alternative options.";
        $continue = false;
    }
    
    @mysql_select_db("eandb") or die("Unable to select database " . mysql_error());
    //$qstring = "SELECT a.* ,p.* FROM activepropertylist AS a INNER JOIN propertydescriptionlist  AS p ON a.eandbHotelID = p.eandbHotelID WHERE a.City LIKE '" . $term . "' LIMIT 20;";
    $qstring = "SELECT a.EANHotelID AS hotelId, a.Name AS hotelName, a.HighRate AS hRate, a.LowRate AS lRate, a.StarRating AS rating, CONCAT(SUBSTRING_INDEX(prop.PropertyDescription,' ',25),' ','...') AS shortDesc, h.ThumbnailURL AS thumbnailUrl FROM activepropertylist AS a INNER JOIN propertydescriptionlist AS prop ON a.EANHotelID = prop.EANHotelID INNER JOIN hotelimagelist AS h on h.EANHotelID = a.EANHotelID WHERE a.City = '" . $term . "' AND a.SupplierType = 'ESR' AND h.DefaultImage = 1 LIMIT 10;";
    $result = mysql_query($qstring) or die(mysql_error()); //query the database for entries containing the term
    $i = 0;
    $test = array();
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $test[$i] = $row;
		$test[$i++]["rateCurrencyCode"] = "USD";
    }
    

    /* End of destination check */
    if (isset($_SESSION["hotelinfo"])) {
        unset($_SESSION["hotelinfo"]);
    }

    /* POST VARIABLES */
    if (!empty($_POST['destination']) && $continue == true) {
        $destination = urlencode($_POST["destination"]);
        $_SESSION["search"]["destination"] =  $destination;
    } elseif ($continue == true) {
        $_SESSION['searchError'] = "There was an error related to the destination you have selected";
        $continue = false;
    }

    if (!empty($_POST["check-in"]) && Utils::is_date($_POST["check-in"]) && $continue == true) {
        $checkIn = $_POST["check-in"];
        $_SESSION["search"]["checkIn"] = $checkIn;
    } elseif ($continue == true) {
        $_SESSION['searchError'] = "The check-in date you have entered is invalid.";
        $continue = false;
    }

    if (!empty($_POST["check-out"]) && Utils::is_date($_POST["check-out"]) && $continue == true) {
        $checkOut = $_POST["check-out"];
        $_SESSION["search"]["checkOut"] = $checkOut;
    } elseif ($continue == true) {
        $_SESSION['searchError'] = "The check-out date you have entered is invalid.";
        $continue = false;
    }

    if (!empty($_POST['room_noumber']) && $continue == true) {
        $roomCount = $_POST['room_noumber'];
        $_SESSION["search"]["roomCount"] = $roomCount;
    } elseif ($continue == true) {
        $_SESSION['searchError'] = "There was an error related to the number of rooms you have selected";
        $continue = false;
    }

    for ($i = 1; $i <= $roomCount; $i++) {
        $rooms[$i] = $_POST["room$i"];
        $_SESSION["rooms"][$i]["adults"] = isset($_POST["room$i"]["adultsCount"]) ? $_POST["room$i"]["adultsCount"] : "";
        $_SESSION["rooms"][$i]["children"] = isset($_POST["room$i"]["childrenCount"]) ? $_POST["room$i"]["childrenCount"] : "";
        $_SESSION["rooms"][$i]["ages_array"] = array();
        $_SESSION["rooms"][$i]["ages_string"] = "";

        for ($k = 1; $k <= $_SESSION["rooms"][$i]["children"]; $k++) {
            $_SESSION["rooms"][$i]["ages_string"] .= isset($_POST["room$i"]["children$k"]) ? $_POST["room$i"]["children$k"] . "," : "";
            $_SESSION["rooms"][$i]["ages_array"][$k] = isset($_POST["room$i"]["children$k"]) ? (int) $_POST["room$i"]["children$k"] : 0;
        }
        $_SESSION["rooms"][$i]["ages_string"] = substr($_SESSION["rooms"][$i]["ages_string"], 0, -1);

        // OLD CODE - NEED TO DESTROY
        $_SESSION["room$i" . "_adults"] = $_POST["room$i"]["adultsCount"];
        $_SESSION["room$i" . "_children"] = $_POST["room$i"]["childrenCount"];
        $_SESSION["room$i" . "_ages"] = "";
        for ($k = 1; $k <= $_SESSION["room$i" . "_children"]; $k++) {
            $_SESSION["room$i" . "_ages"] .= $_POST["room$i"]["children$k"] . ",";
        }
        for ($j = $rooms[$i]["childrenCount"] + 1; $j <= 3; $j++) {
            $rooms[$i]["children$j"] = "";
        }
        $_SESSION["room$i" . "_ages"] = substr($_SESSION["room$i" . "_ages"], 0, -1);
    }

    if ($continue) {
        $smartyData = $smarty->createData();
        $hotelArray = array();
        $filter = new Filter();

        $filter->supplierType = "E";
        $filter->RoomGroup = new RoomGroup($rooms, $roomCount);
        
        $options = "DEFAULT";
        $optimizationState = NULL;

        $api = new APIObject();
        $filter = new Filter();

        $filter->supplierType = "E";
        $filter->RoomGroup = new RoomGroup($rooms, $roomCount);
        $hotelRes = $api->GetHotelList_City($checkIn, $checkOut, $numberOfResults, $destination, $stateProvince, $countryCode, $filter, $options, $optimizationState);

        


        // ERROR MANAGEMENT
        if (empty($hotelRes->HotelList->HotelSummary)) {
            $_SESSION['searchError'] = "Sorry, no available hotels were found for the options you have selected. Please try alternative options.";
            header("Location: $errorUrl");
        }

        $hotelRes->HotelList->HotelSummary = (!is_array($hotelRes->HotelList->HotelSummary)) ? array($hotelRes->HotelList->HotelSummary) : $hotelRes->HotelList->HotelSummary;

        for ($index = 0; $index < count($hotelRes->HotelList->HotelSummary); $index++) {
            $rateInfos = isset($hotelRes->HotelList->HotelSummary[$index]->RoomRateDetailsList->RoomRateDetails->RateInfos->RateInfo->ChargeableRateInfo) ? 
                    $hotelRes->HotelList->HotelSummary[$index]->RoomRateDetailsList->RoomRateDetails->RateInfos->RateInfo->ChargeableRateInfo: null;

            $hotelArray[$index]["thumbnailUrl"] = isset($hotelRes->HotelList->HotelSummary[$index]->thumbNailUrl) ?
                    "http://images.travelnow.com" . substr_replace($hotelRes->HotelList->HotelSummary[$index]->thumbNailUrl, "g", -5, 1) : "";
            $hotelArray[$index]["hotelName"] = isset($hotelRes->HotelList->HotelSummary[$index]->name) ?
                    $hotelRes->HotelList->HotelSummary[$index]->name : "";
            $hotelArray[$index]["shortDesc"] = isset($hotelRes->HotelList->HotelSummary[$index]->shortDescription) ?
                    $hotelRes->HotelList->HotelSummary[$index]->shortDescription . " ..." : "";
            $hotelArray[$index]["rating"] = isset($hotelRes->HotelList->HotelSummary[$index]->hotelRating) ?
                    (int) round((float) $hotelRes->HotelList->HotelSummary[$index]->hotelRating) : "";
            $hotelArray[$index]["supplierType"] = isset($hotelRes->HotelList->HotelSummary[$index]->supplierType) ?
                    $hotelRes->HotelList->HotelSummary[$index]->supplierType : "";
            $hotelArray[$index]["lRate"] = isset($hotelRes->HotelList->HotelSummary[$index]->lowRate) ?
                    $hotelRes->HotelList->HotelSummary[$index]->lowRate : "";
            $hotelArray[$index]["hRate"] = isset($hotelRes->HotelList->HotelSummary[$index]->highRate) ?
                    $hotelRes->HotelList->HotelSummary[$index]->highRate : "";
            $hotelArray[$index]["rateCurrencyCode"] = isset($hotelRes->HotelList->HotelSummary[$index]->rateCurrencyCode) ?
                    $hotelRes->HotelList->HotelSummary[$index]->rateCurrencyCode : "";
            $hotelId = isset($hotelRes->HotelList->HotelSummary[$index]->hotelId) ? $hotelRes->HotelList->HotelSummary[$index]->hotelId : "";
            $hotelArray[$index]["hotelId"] = $hotelId;
            //$hotelArray[$index]["nrOfPictures"] = 10;
            $hotelArray[$index]["checkin"] = $checkIn;
            $hotelArray[$index]["checkout"] = $checkOut;
            //$hotelArray[$index]["smokingPreferences"] = "";

            if (empty($rateInfos->{'@surchargeTotal'})) {
                $rateInfos->{'@surchargeTotal'} = 'Not specified';
            }
            $hotelArray[$index]['rateInfos'] = array(
                'total' => isset($rateInfos->{'@total'}) ? $rateInfos->{'@total'} : "",
                'nightlyRateTotal' => isset($rateInfos->{'@nightlyRateTotal'}) ? $rateInfos->{'@nightlyRateTotal'} : "",
                'surchargeTotal' => isset($rateInfos->{'@surchargeTotal'}) ? $rateInfos->{'@surchargeTotal'} : "",
                'currencyCode' => isset($rateInfos->{'@currencyCode'}) ? $rateInfos->{'@currencyCode'} : "",
            );
        }
       
        $smartyData->assign("hotelArray", $hotelArray);
        $smartyData->assign("server", 'bookingPage.php');
        $smarty->display('preHeader.tpl');
        echo '<body>';
        $smarty->display('header.tpl');
        $smarty->display("hotellist_new.tpl", $smartyData);
        $smarty->display('flashyBox.tpl');
        $smarty->display('footer.tpl');
        echo '</body>';

        $_SESSION["roomsNumber"] = $roomCount;
        for ($index = 1; $index <= $roomCount; $index++) {
            $_SESSION["roomsData"][$index]["adults"] = $rooms[$index]["adultsCount"];
            $_SESSION["roomsData"][$index]["childrenNr"] = $rooms[$index]["childrenCount"];
            $_SESSION["roomsData"][$index]["childrenAge"] =
                    $rooms[$index]["children1"] . "," .
                    $rooms[$index]["children2"] . "," .
                    $rooms[$index]["children3"];
        }
        //$_SESSION["checkIn"] = $checkIn;
        //$_SESSION["checkOut"] = $checkOut;
        $_SESSION["roomGroup"] = serialize($filter->RoomGroup);
    } else {
        header("Location: $errorUrl");
    }
 ?>
</html>